#include "SimpleBuzzer.h"

SimpleBuzzer::SimpleBuzzer(uint8_t pin, bool isActive) : _pin(pin), _isActive(isActive), _state(false) {
}

void SimpleBuzzer::begin() {
    pinMode(_pin, OUTPUT);
    off(); // 初始状态为关闭
}

void SimpleBuzzer::on() {
    digitalWrite(_pin, _isActive ? HIGH : LOW);
    _state = true;
}

void SimpleBuzzer::off() {
    digitalWrite(_pin, _isActive ? LOW : HIGH);
    _state = false;
}

void SimpleBuzzer::beep(unsigned long duration) {
    on();
    delay(duration);
    off();
}

void SimpleBuzzer::multiBeep(uint8_t times, unsigned long onDuration, unsigned long offDuration) {
    for (uint8_t i = 0; i < times; i++) {
        on();
        delay(onDuration);
        off();
        if (i < times - 1) { // 在最后一次蜂鸣后不延迟
            delay(offDuration);
        }
    }
}

void SimpleBuzzer::playMelody(int* melody, int* durations, int size) {
    for (int i = 0; i < size; i++) {
        // 对于无源蜂鸣器，可以使用tone函数产生不同频率的声音
        if (!_isActive && melody[i] > 0) {
            tone(_pin, melody[i], durations[i]);
        } else {
            // 对于有源蜂鸣器，只能开关控制
            beep(durations[i]);
        }
        
        // 两个音符之间添加一点延迟
        delay(durations[i] * 1.1);
        
        // 确保停止tone
        if (!_isActive) {
            noTone(_pin);
        }
    }
} 